package Device.Card.UsbCard;

/**
 * Created by 王彦鹏 on 2017-11-18.
 */

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import Const.PublicDefine;
import Device.Card.IUsbDevice;
import Struct.BinaryType;
import Helper.Log;
import Interface.IBrushCardEvent;
import Interface.ICard;
import Interface.IUsbDeviceEvent;

public class UsbReader extends UsbHidDevice implements ICard, IUsbDevice {
    /**
     * 盈加宝盒的 Vid 与 Pid
     */
    private int vId=0x0483;
    private  int pId=0x1240;
    //命令定义
    private byte CMD_ReadState=0x01;//获取读卡器状态
    private  byte CMD_SEARCHCARD = 0x06;       //寻卡
    private  byte CMD_BEEP = 0x02;             //蜂鸣
    private  byte CMD_RESETCARD = 0x07;        //复位卡
    private  byte CMD_VERIFYSECTORKEY = 0x0A;          //校验密码
    private  byte CMD_READBLOCK = 0x0B;        //读块
    private  byte CMD_WRITEBLOCK = 0x0C;       //写块

    /**
     * 读扇区
     */
    private byte CMD_READSECT=0x14;

    /**
     * 读扇区
     */
    private byte CMD_WRITESECT=0x15;

    private boolean CardExist=false;
    protected Object syncobj = new Object();
    private byte[] mCardNo=new byte[4];
    protected String logTag="UsbReader";
    private ExecutorService executor;


    public void destory()
    {
        synchronized (syncobj) {
            executor.shutdown();
        }
        CloseUsb(this.usbDevice);
    }
    /**
     * 关闭设备
     * @param device
     */
    @Override
    public void CloseUsb(UsbDevice device){
        if (device.getProductId()==pId && device.getVendorId()==vId) {
            if (isConnection) {
                isConnection = false;
                if (mctx instanceof IUsbDeviceEvent) {
                    ((IUsbDeviceEvent) mctx).UsbLineOffEvent(device, usbDeviceConnection);
                }
                usbDeviceConnection.close();
            }
            executor.shutdown();
        }
    }
    //查找指定的HID设备
    @Override
    public void OpenDevice(UsbDevice device){
        if (device!=null &&(device.getProductId()!=pId || device.getVendorId()!=vId)) {
            return;
        }
        if (isConnection) {
            if (mctx instanceof IUsbDeviceEvent) {
                ((IUsbDeviceEvent) mctx).UsbLineOnEvent(usbDevice, usbDeviceConnection);
            }
            return;
        }
         HashMap<String,UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while(deviceIterator.hasNext()){
            usbDevice = deviceIterator.next();
            if((usbDevice.getVendorId()==vId)&&(usbDevice.getProductId()==pId))
            {
                if (!usbManager.hasPermission(usbDevice)) {
                    usbManager.requestPermission(usbDevice, mPermissionIntent);
                }
                else
                {
                    UsbInterface usb = usbDevice.getInterface(0);
                    usbDeviceConnection= OpenUsb(usb);
                    if (usbDeviceConnection!=null)
                    {
                        isConnection=true;
                        if (mctx instanceof IUsbDeviceEvent)
                        {
                            ((IUsbDeviceEvent) mctx).UsbLineOnEvent(usbDevice,usbDeviceConnection);
                        }
                    }
                    executor = Executors.newSingleThreadExecutor();
                    executor.execute(CheckCardThread);
                }
                return ;
            }
        }
        return ;
    }


    public void SetIntent(Context ctx,Intent intent) throws InterruptedException {
        mctx = ctx;
        this.intent = intent;
        if (mctx == null) {
            return;
        }

        if (!isConnection) {
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            mctx.registerReceiver(this, filter);
            mPermissionIntent = PendingIntent.getBroadcast(mctx, 0, new Intent(ACTION_USB_PERMISSION), 0);
            usbManager = (UsbManager) mctx.getSystemService(Context.USB_SERVICE);
            usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            OpenDevice(usbDevice);
        }

    }

    @Override
    public UsbDeviceConnection OpenUsb(UsbInterface Iusb) {
        UsbDeviceConnection conn= super.OpenUsb(Iusb);
        return conn;
    }
    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            try {
                super.handleMessage(msg);
                if (intent==null)
                {
                    return;
                }
                if (msg.what==1) {
                    ((IBrushCardEvent)mctx).BrushIn(null);
                } else {
                    ((IBrushCardEvent)mctx).BrushOut(null);
                }
                //this.sendEmptyMessageDelayed(msg.arg1, 50);
            } catch (Exception e) {
                Log.write(logTag, e.toString());
            }
        }
    };

    private Runnable CheckCardThread=new Runnable() {
        @Override
        public void run() {
            Message msg = new Message();
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            Object obj=new Object();
            while (!executor.isShutdown()) {
                if (mctx != null) {
                    if (intent!=null) {
                        synchronized (syncobj) {
                            try {
                                if (mctx instanceof IBrushCardEvent) {
                                    if (findCard()) {
                                        if (!CardExist) {
                                            Log.write(logTag, String.format("卡移入，处理对象：%s", mctx.getClass().getName()));
                                            CardExist = true;
                                            msg.arg1 = 1;
                                            msg.obj = intent;
                                            handle.sendEmptyMessage(msg.arg1);
                                        }

                                    } else {
                                        if (CardExist) {
                                            Log.write(logTag, String.format("卡移出，处理对象：%s", mctx.getClass().getName()));
                                            CardExist = false;
                                            msg.arg1 = 0;
                                            msg.obj = intent;
                                            handle.sendEmptyMessage(msg.arg1);
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                    synchronized (obj)
                    {
                        try {
                            obj.wait(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    };

    private boolean findCard() {
        synchronized (syncobj) {
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_SEARCHCARD);
            rc.setInDataLen(1);
            rc.getInData()[0] = 0;
            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return false;
            }
            if (rc.getOutData()[0] == 0) {
                System.arraycopy(rc.getOutData(), 1, mCardNo, 0, 4);
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public boolean ExistsCard() {
        return CardExist;
    }

    @Override
    public byte[] GetCardId() {
        return mCardNo;
    }

    @Override
    public long GetCardNo() {
        BinaryType bt=new BinaryType(4,int.class);
        bt.setData(mCardNo);
        return bt.getInt();
    }
    //验证扇区密码
    //keyType 密码类型 0 A密码  1 B密码
    //sectorIndex 扇区号
    //key 密码 6字节
    private int verifySectorKey(byte keyType, byte sectorIndex, byte [] key)
    {
        synchronized (syncobj) {
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_VERIFYSECTORKEY);
            rc.setInDataLen(8);
            rc.getInData()[0] = keyType;
            rc.getInData()[1] = sectorIndex;
            for (int i = 0; i < 6; i++) {
                rc.getInData()[2 + i] = key[i];
            }
            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return iRet;
            } else {
                return rc.getOutData()[0];
            }
        }
    }

    @Override
    public void SetBrushEvent(IBrushCardEvent event) {

    }

    @Override
    public byte[] GetReaderState() {
        synchronized (syncobj) {
            Log.write(logTag, "读扇设备状态");
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_ReadState);
            rc.setInDataLen(0);

            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return null;
            }
            if (rc.getOutData()[0] != 0) {
                return null;
            }
            byte[] data = new byte[30];
            System.arraycopy(rc.getOutData(), 1, data, 0, 30);
            return data;
        }
    }

    @Override
    public byte[] ReadSector(int SectorNo, byte[] readkey) throws IOException {
        synchronized (syncobj) {
            Log.write(logTag, "读扇区");
            if (verifySectorKey((byte) 0, (byte) SectorNo, readkey) != 0) {
                return null;
            }

            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_READSECT);
            rc.setInDataLen(1);
            rc.getInData()[0] = (byte) SectorNo;
            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return null;
            }
            if (rc.getOutData()[0] != 0) {
                return null;
            }
            byte[] data = new byte[48];
            System.arraycopy(rc.getOutData(), 1, data, 0, 48);
            return data;
        }
    }

    @Override
    public byte[] ReadBlock(int BlockNo, byte[] readkey) throws IOException {
        synchronized (syncobj) {
            Log.write(logTag, "读块");
            if (verifySectorKey((byte) 0, (byte) (BlockNo / 4), readkey) != 0) {
                resetCard((byte)100);
                return null;
            }

            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_READBLOCK);
            rc.setInDataLen(1);
            rc.getInData()[0] = (byte) BlockNo;
            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return null;
            }
            if (rc.getOutData()[0] != 0) {
                return null;
            }
            byte[] data = new byte[16];
            System.arraycopy(rc.getOutData(), 1, data, 0, 16);
            return data;
        }
    }

    @Override
    public int WriteSector(int SectorNo, byte[] Data, byte[] writekey) throws IOException {
        synchronized (syncobj) {
            Log.write(logTag, "写扇区");
            if (verifySectorKey((byte) 0, (byte) SectorNo, writekey) != 0) {
                return 1;
            }
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_WRITESECT);
            rc.setInDataLen(49);
            rc.getInData()[0] = (byte) SectorNo;
            for(int i=0;i<48;i++)
            {
                rc.getInData()[i+1]=Data[i];
            }

            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return iRet;
            }
            if (rc.getOutData()[0] != 0) {
                return rc.getOutData()[0];
            }
            return 0;
        }
    }

    @Override
    public int WriteBlock(int BlockNo, byte[] Data, byte[] writekey) throws IOException {
        synchronized (syncobj) {
            Log.write(logTag, "写块");
            if (verifySectorKey((byte) 0, (byte) (BlockNo / 4), writekey) != 0) {
                return 1;
            }
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_WRITEBLOCK);
            rc.setInDataLen(17);
            rc.getInData()[0] = (byte) BlockNo;
            for(int i=0;i<16;i++)
            {
                rc.getInData()[i+1]=Data[i];
            }

            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return iRet;
            }
            if (rc.getOutData()[0] != 0) {
                return rc.getOutData()[0];
            }
            return 0;
        }
    }

    @Override
    public boolean AuthentReadKey(int SectorNo, byte[] Key) throws Exception {
        return false;
    }

    @Override
    public boolean AuthentWruteKey(int SectorNo, byte[] Key) throws Exception {
        return false;
    }

    @Override
    public boolean connected() {
        return isConnection;
    }

    @Override
    public int GetSectorCount() {
        return 0;
    }

    @Override
    public int GetBlockCount() {
        return 0;
    }


    //卡复位
    public int resetCard(byte _Msec)
    {
        synchronized (syncobj) {
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_RESETCARD);
            rc.setInDataLen(1);
            rc.getInData()[0] = _Msec;
            int iRet = SendCommand(rc);
            if (iRet != 0) {
                return iRet;
            } else {
                return rc.getOutData()[0];
            }
        }
    }

    public void beep(int ms){
        synchronized (syncobj) {
            ReaderCommand rc = new ReaderCommand();
            rc.setCmdCode(CMD_BEEP);
            rc.setInDataLen(2);
            rc.getInData()[0] = (byte) ms;
            rc.getInData()[1] = (byte) (ms >> 8);
            int iRet = SendCommand(rc);
        }
    }

    @Override
    public Object CardSyncObj() {
        return syncobj;
    }


}
